﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace LynxWebLog.Controllers
{
    [Authorize(Roles = "BlogUser,BlogAdmin")]
    public class BlogLayoutDataController : Controller
    {
        List<BlogLayoutData> _lbld = new List<BlogLayoutData>();
        HttpClient client = ClientUtility.BlogAPIClient();
        //
        // GET: /BlogLayoutData/
        //[Authorize(Roles="BlogUser")]
        public async Task<ActionResult> Index()
        {
            try {
                ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
                HttpResponseMessage resp = await client.GetAsync("api/BlogLayoutData/?$filter=username eq '" + User.Identity.Name + "'");
                resp.EnsureSuccessStatusCode();

                IEnumerable<BlogLayoutData> bld = await resp.Content.ReadAsAsync<IEnumerable<BlogLayoutData>>();
                _lbld = bld.ToList();
            }
            catch (SerializationException ex) {
                Debug.Print(ex.Message);
            }
            catch (HttpRequestException ex) {
                Debug.Print(ex.Message);
            }

            return View(_lbld);
        }

        //
        // GET: /BlogLayoutData/Details/5
        public async Task<ActionResult> Details(int id)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            BlogLayoutData bld = new BlogLayoutData();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogLayoutData/?$filter=username eq '" + User.Identity.Name + "' and bloglayoutid eq " + id);
                resp.EnsureSuccessStatusCode();

                bld = (await resp.Content.ReadAsAsync<IEnumerable<BlogLayoutData>>()).FirstOrDefault();
            }
            catch (SerializationException ex) {
                Debug.Print(ex.Message);
            }
            catch (HttpRequestException ex) {
                Debug.Print(ex.Message);
            }
            return View(bld);
        }

        //
        // GET: /BlogLayoutData/Create
        public ActionResult Create()
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            return View();
        }

        //
        // POST: /BlogLayoutData/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Create(HttpPostedFileBase header_image, BlogLayoutData bld)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            if (header_image != null) {
                bld.header_image = header_image.FileName;
            }
            if (ModelState.IsValid) {
                try {
                    HttpResponseMessage resp = await client.PostAsXmlAsync("api/BlogLayoutData", bld);
                    resp.EnsureSuccessStatusCode();

                    //create user directory if it does not exist under /App_Data/Blogs
                    string path = Server.MapPath("~/BlogResources");
                    string userpath = Path.Combine(path, bld.username);
                    DirectoryInfo userDir = new DirectoryInfo(userpath);
                    if (!userDir.Exists) {
                        userDir.Create();
                    }

                    //create blog directory if it does not exist under the user directory
                    string blogpath = Path.Combine(userpath, bld.blogname);
                    DirectoryInfo blogDir = new DirectoryInfo(blogpath);
                    if (!blogDir.Exists) {
                        blogDir.Create();
                    }

                    //post the image file to the blog directory
                    if (!String.IsNullOrEmpty(bld.header_image)) {
                        string imagepath = Path.Combine(blogpath, bld.header_image);
                        header_image.SaveAs(imagepath);
                    }

                    //create the css overrides in the blog directory
                    string csspath = Path.Combine(blogpath, "LocalBlog.css");
                    CssStrings cs = new CssStrings();
                    cs.SetColors(bld.color_primary, bld.color_primary_dark, bld.color_background, bld.color_border, bld.color_border_dark);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(cs.CreateCss());
                    sb.AppendLine("/* Above this line is automatically generated by program for colors */");
                    sb.AppendLine("/* Below this line is custom css entered in blog Layout Data */");
                    sb.Append(bld.custom_css);
                    FileInfo fi = new FileInfo(csspath);
                    StreamWriter sw = fi.CreateText();
                    sw.Write(sb.ToString());
                    sw.Close();

                    return RedirectToAction("Index");
                }
                catch (SystemException ex) {
                    Debug.Print(ex.Message);
                    //return View();
                }
            }
            return View();
        }

        //
        // GET: /BlogLayoutData/Edit/5
        public async Task<ActionResult> Edit(int id)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            BlogLayoutData bld = new BlogLayoutData();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogLayoutData/?$filter=username eq '" + User.Identity.Name + "' and bloglayoutid eq " + id);
                resp.EnsureSuccessStatusCode();

                bld = (await resp.Content.ReadAsAsync<IEnumerable<BlogLayoutData>>()).FirstOrDefault();
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
            }
            return View(bld);
        }

        //
        // POST: /BlogLayoutData/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Edit(HttpPostedFileBase header_image, BlogLayoutData bld)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            if (header_image != null) {
                bld.header_image = header_image.FileName;
            }
            try {
                HttpResponseMessage resp = await client.PutAsXmlAsync("api/BlogLayoutData/" + bld.bloglayoutid, bld);
                resp.EnsureSuccessStatusCode();

                //post the image file to the blog directory
                if (!String.IsNullOrEmpty(bld.header_image)) {
                    string imagepath = Path.Combine(Server.MapPath("~/BlogResources"), bld.username, bld.blogname, bld.header_image);
                    header_image.SaveAs(imagepath);
                }

                //update the css overrides in the blog directory
                string csspath = Path.Combine(Server.MapPath("~/BlogResources"), bld.username, bld.blogname, "LocalBlog.css");
                CssStrings cs = new CssStrings();
                cs.SetColors(bld.color_primary, bld.color_primary_dark, bld.color_background, bld.color_border, bld.color_border_dark);
                StringBuilder sb = new StringBuilder();
                sb.Append(cs.CreateCss());
                sb.AppendLine("/* Above this line is automatically generated by program for colors */");
                sb.AppendLine("/* Below this line is custom css entered in blog Layout Data */");
                sb.Append(bld.custom_css);
                FileInfo fi = new FileInfo(csspath);
                StreamWriter sw = fi.CreateText();
                sw.Write(sb.ToString());
                sw.Close();
                return RedirectToAction("Index");
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
                return View(bld);
            }
        }

        //
        // GET: /BlogLayoutData/Delete/5
        public async Task<ActionResult> Delete(int id)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            BlogLayoutData bld = new BlogLayoutData();
            try {
                HttpResponseMessage resp = await client.GetAsync("api/BlogLayoutData/?$filter=username eq '" + User.Identity.Name + "' and bloglayoutid eq " + id);
                resp.EnsureSuccessStatusCode();

                bld = (await resp.Content.ReadAsAsync<IEnumerable<BlogLayoutData>>()).FirstOrDefault();
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
            }
            return View(bld);
        }

        //
        // POST: /BlogLayoutData/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> DeleteConfirmed(int bloglayoutid)
        {
            try
            {
                HttpResponseMessage resp = await client.DeleteAsync("api/BlogLayoutData/" + bloglayoutid);
                resp.EnsureSuccessStatusCode();

                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Delete");
            }
        }
    }
}
